import socket, unicodedata, re, time
# -*- coding: utf-8 -*-
#Работает!

def _createKey(lock):# за код спасибо Окси    
                key = {}
                for i in xrange(1, len(lock)):
                        key[i] = ord(lock[i]) ^ ord(lock[i-1])
                key[0] = ord(lock[0]) ^ ord(lock[len(lock)-1]) ^ ord(lock[len(lock)-2]) ^ 5
                for i in xrange(0, len(lock)):
                        key[i] = ((key[i]<<4) & 240) | ((key[i]>>4) & 15)

                out = ''
                for i in xrange(0, len(lock)):
                        out += unichr(key[i])

                out = out.replace(u'\0', u'/%DCN000%/').replace(u'\5', u'/%DCN005%/').replace(u'\44', u'/%DCN036%/')
                out = out.replace(u'\140', u'/%DCN096%/').replace(u'\174', u'/%DCN124%/').replace(u'\176', u'/%DCN126%/')

                return out

#http://www.teamfair.info/DC-Protocol.htm
#http://www.teamfair.info/wiki/index.php?title=Main_Page
HOST='avangard.no-ip.org'
PORT=411
NICK='Tachicoma'
DESCR=''
TAG='<PyDC++BOT V:0.001>'



sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST,PORT))
print sock.recv(1024)
key =_createKey('EXTENDEDPROTOCOL_verlihub').encode("utf-8")
print sock.recv(1024)
sock.send('$Key %s|$ValidateNick %s|'%(key,NICK))
print sock.recv(1024)
#$MyINFO $ALL Major [9]<ApexDC++ V:0.4.0,M:A,H:28/20/0,S:48>$ $0.2    $$77690695918$
sock.send('$Version 1,0091|$MyINFO $ALL %s %s%s$ $0$$0$|' %(NICK,DESCR,TAG))
#print sock.recv(1024)

#print sock.recv(2048).encode('cp1251')
#sock.send('<PyDCPP> desu|')

def utf8_cp1251(text):
    u=unicode(text, 'utf8')
    cyrillic_cp1251=u.encode('cp1251')
    return cyrillic_cp1251

def cp1251_utf8(text):
    cyrillic_cp1251=unicode(text, 'cp1251')
    text=cyrillic_cp1251.encode('utf8')
    return text

while True:
    s=sock.recv(1024)
    summon=re.findall('<Apkawa> MAKI!', s)
    kill=re.findall('<Apkawa> MAKI kill self!', s)
    text_bye='<MAKI> Хозяин приказал умереть. Я сделал себе сеппуку. =_=|'
#    print sock.recv(1024).encode('cp1251')
    if summon != []:
        text_summon='<MAKI> Звали, хозяин?|'
        sock.send(utf8_cp1251(text_summon))
        #print utf8_cp1251(text)
    if kill != []:
        text_bye='<MAKI> Хозяин приказал умереть. Я сделал себе сеппуку. =_=|'
        sock.send(utf8_cp1251(text_bye))
    print  cp1251_utf8(sock.recv(1024))

time.sleep(5)
sock.close()




def __init__(self):
                self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self._cache = ""

                self._codepage = None
                self._address = None

                self._state = DCSocket.ST_DISCONNECTED
def connect(self, address, codepage):
                self._address = address
                self._codepage = codepage

                try:
                        res = self._socket.connect(self._address)
                except socket.error, k:
                        raise Error(k.args[0], k.args[1])            
